<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html>
<head>
<title>PySide Widgets</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="PySide, learn PySide, Widgets, tutorial, Python, Linux, GUI">
<meta name="description" content="This part of the PySide tutorial covers PySide Widgets.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container2">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content2">


<a href="/" title="Home">Home</a>&nbsp;
<a href=".." title="Home">Contents</a>


<h1>PySide Widgets</h1>


<p>
Widgets are basic building blocks of an application. The PySide 
programming toolkit has a wide range of various widgets. Buttons, 
check boxes, sliders, list boxes etc.
Everything a programmer needs for his job. In this section of 
the tutorial, we will describe several useful widgets.
Namely <code>QtGui.QCheckBox</code>, <code>ToggleButton</code>, 
<code>QtGui.QSlider</code>, <code>QtGui.QProgressBar</code> 
and a <code>QtGui.QCalendarWidget</code>.
</p>

<div class="big_hor">
<script type="text/javascript"><!--
google_ad_client = "ca-pub-9706709751191532";
/* big_horizontal */
google_ad_slot = "2904953388";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>


<h2>QtGui.QCheckBox</h2>

<p>
<code>QtGui.QCheckBox</code> is a widget that has two states. On and Off. 
It is a box with a label. Checkboxes are typically used to represent 
features in an application that can be enabled or 
disabled without affecting others.
</p>

<pre class="code">
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode PySide tutorial 

In this example, a QtGui.QCheckBox widget
is used to toggle the title of a window.

author: Jan Bodnar
website: zetcode.com 
last edited: August 2011
"""

import sys
from PySide import QtGui, QtCore

class Example(QtGui.QWidget):
    
    def __init__(self):
        super(Example, self).__init__()
        
        self.initUI()
        
    def initUI(self):      

        cb = QtGui.QCheckBox('Show title', self)
        cb.move(20, 20)
        cb.toggle()
        cb.stateChanged.connect(self.changeTitle)
        
        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('QtGui.QCheckBox')
        self.show()
        
    def changeTitle(self, state):
      
        if state == QtCore.Qt.Checked:
            self.setWindowTitle('Checkbox')
        else:
            self.setWindowTitle('')
        
def main():
    
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

</pre>

<p>
In our example, we will create a checkbox that will toggle the window title. 
</p>

<pre class="explanation">
cb = QtGui.QCheckBox('Show title', self)
</pre>

<p>
This is the <code>QtGui.QCheckBox</code> constructor.
</p>

<pre class="explanation">
cb.toggle()
</pre>

<p>
We set the window title, so we must also check the checkbox. 
</p>

<pre class="explanation">
cb.stateChanged.connect(self.changeTitle)
</pre>

<p>
We connect the user defined <code>changeTitle()</code> 
method to the <code>stateChanged</code> signal.
The changeTitle() method will toggle the window title.
</p>

<pre class="explanation">
def changeTitle(self, state):
  
    if state == QtCore.Qt.Checked:
        self.setWindowTitle('Checkbox')
    else:
        self.setWindowTitle('')
</pre>

<p>
We receive the state of the check box in the state variable. 
If it is set, we set a title of the window. Otherwise, we
use an empty string as a title. 
</p>

<img src="/img/gui/pyside/checkbox.png" alt="QtGui.QCheckBox">
<div class="figure">Figure: QtGui.QCheckBox</div>


<h2>ToggleButton</h2>

<p>
PySide has no widget for a ToggleButton. To create a ToggleButton, we 
use a <code>QtGui.QPushButton</code> in a special mode.
ToggleButton is a button that has two states. Pressed and not pressed. 
You toggle between these two states by clicking on it. There are situations 
where this functionality fits well.
</p>

<pre class="code">
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode PySide tutorial 

In this example, we create three toggle buttons.
They will control the background color of a 
QtGui.QFrame. 

author: Jan Bodnar
website: zetcode.com 
last edited: August 2011
"""

import sys
from PySide import QtGui, QtCore

class Example(QtGui.QWidget):
    
    def __init__(self):
        super(Example, self).__init__()
        
        self.initUI()
        
    def initUI(self):      

        self.col = QtGui.QColor(0, 0, 0)       

        redb = QtGui.QPushButton('Red', self)
        redb.setCheckable(True)
        redb.move(10, 10)

        redb.clicked[bool].connect(self.setColor)

        greenb = QtGui.QPushButton('Green', self)
        greenb.setCheckable(True)
        greenb.move(10, 60)

        greenb.clicked[bool].connect(self.setColor)

        blueb = QtGui.QPushButton('Blue', self)
        blueb.setCheckable(True)
        blueb.move(10, 110)

        blueb.clicked[bool].connect(self.setColor)

        self.square = QtGui.QFrame(self)
        self.square.setGeometry(150, 20, 100, 100)
        self.square.setStyleSheet("QWidget { background-color: %s }" %  
            self.col.name())
        
        self.setGeometry(300, 300, 280, 170)
        self.setWindowTitle('Toggle button')
        self.show()
        
    def setColor(self, pressed):
        
        source = self.sender()
        
        if pressed:
            val = 255
        else: val = 0
                        
        if source.text() == "Red":
            self.col.setRed(val)                
        elif source.text() == "Green":
            self.col.setGreen(val)             
        else:
            self.col.setBlue(val) 
            
        self.square.setStyleSheet("QFrame { background-color: %s }" %
            self.col.name())  
        
def main():
    
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
</pre>

<p>
In our example, we create three ToggleButtons. We also create a 
<code>QtGui.QFrame</code> widget. We set the background color of the widget
to black. The togglebuttons will toggle the red, green and blue 
parts of a color value. The background color will
depend on which togglebuttons we have pressed.  
</p>

<pre class="explanation">
self.col = QtGui.QColor(0, 0, 0)  
</pre>

<p>
This is the initial color value. It is black.
</p>

<pre class="explanation">
greenb = QtGui.QPushButton('Green', self)
greenb.setCheckable(True)
</pre>

<p>
To create a ToggleButton, we create a <code>QtGui.QPushButton</code> and make it 
checkable by calling the <code>setCheckable()</code> method.
</p>

<pre class="explanation">
greenb.clicked[bool].connect(self.setColor)
</pre>

<p>
We connect a <code>clicked[bool]</code> signal to our user defined method.
Note that this signal type sends a bool argument to the method. The argument
value is true or false, depending on the state of the button, e.g. if 
it is checked/toggled or not. 
</p>


<pre class="explanation">
source = self.sender()
</pre>

<p>
We get the sender of the signal. It is the button, which was toggled.
</p>

<pre class="explanation">
if source.text() == "Red":
    self.col.setRed(val)   
</pre>

<p>
In case it was a red button, we update the red part of the color accordingly.
</p>

<pre class="explanation">
self.square.setStyleSheet("QFrame { background-color: %s }" %
    self.col.name())    
</pre>

<p>
We use stylesheets to change the background color of the <code>QtGui.QFrame</code>
widget. 
</p>


<img src="/img/gui/pyside/togglebutton.png" alt="ToggleButton">
<div class="figure">Figure: ToggleButton</div>


<h2>QtGui.QSlider</h2>

<p>
<code>QtGui.QSlider</code> is a widget that has a simple handle. 
This handle can be pulled back and forth.
This way we are choosing a value for a specific task. Sometimes using a slider is 
more natural, than simply providing a number or using a spin box.
<code>QtGui.QLabel</code> displays text or image. 
</p>

<p>
In our example we will show one slider and one label. This time, the label will 
display an image. The slider will control the
label.
</p>

<pre class="code">
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode PySide tutorial 

This example shows a QtGui.QSlider widget.

author: Jan Bodnar
website: zetcode.com 
last edited: August 2011
"""

import sys
from PySide import QtGui, QtCore

class Example(QtGui.QWidget):
    
    def __init__(self):
        super(Example, self).__init__()
        
        self.initUI()
        
    def initUI(self):      

        sld = QtGui.QSlider(QtCore.Qt.Horizontal, self)
        sld.setFocusPolicy(QtCore.Qt.NoFocus)
        sld.setGeometry(30, 40, 100, 30)
        sld.valueChanged[int].connect(self.changeValue)
        
        self.label = QtGui.QLabel(self)
        self.label.setPixmap(QtGui.QPixmap('mute.png'))
        self.label.setGeometry(160, 40, 80, 30)
        
        self.setGeometry(300, 300, 280, 170)
        self.setWindowTitle('QtGui.QSlider')
        self.show()
        
    def changeValue(self, value):

        if value == 0:
            self.label.setPixmap(QtGui.QPixmap('mute.png'))
        elif value &gt; 0 and value &lt;= 30:
            self.label.setPixmap(QtGui.QPixmap('min.png'))
        elif value &gt; 30 and value &lt; 80:
            self.label.setPixmap(QtGui.QPixmap('med.png'))
        else:
            self.label.setPixmap(QtGui.QPixmap('max.png'))
        
def main():
    
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

</pre>


<p>
In our example we simulate a volume control. By dragging the
handle of a slider, we change an image on the label.
</p>

<pre class="explanation">
sld = QtGui.QSlider(QtCore.Qt.Horizontal, self)
</pre>

<p>
Here we create a horizontal <code>QtGui.QSlider</code>.
</p>

<pre class="explanation">
self.label = QtGui.QLabel(self)
self.label.setPixmap(QtGui.QPixmap('mute.png'))
</pre>

<p>
We create a <code>QtGui.QLabel</code> widget. And set an initial 
mute image to it. 
</p>

<pre class="explanation">
sld.valueChanged[int].connect(self.changeValue)
</pre>

<p>
We connect the <code>valueChanged[int]</code> signal to the user 
defined changeValue() method.
</p>

<pre class="explanation">
if value == 0:
    self.label.setPixmap(QtGui.QPixmap('mute.png'))
...
</pre>

<p>
Based on the value of the slider, we set an image to the label.
In the above code, we set a mute.png image to the label, if the
slider value is equal to zero.
</p>

<img src="/img/gui/pyside/slider.png" alt="QtGui.QSlider widget">
<div class="figure">Figure: QtGui.QSlider widget</div>


<h2>QtGui.QProgressBar</h2>

<p>
A progress bar is a widget that is used, when we process lengthy tasks. 
It is animated so that the user knows, that our task is progressing. 
The <code>QtGui.QProgressBar</code> widget provides a horizontal or 
vertical progress bar in PySide toolkit.
The programmer can set the minimum and maximum values 
for the progress bar. The default values are 0, 99. 
</p>


<pre class="code">
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode PySide tutorial 

This example shows a QtGui.QProgressBar widget.

author: Jan Bodnar
website: zetcode.com 
last edited: August 2011
"""

import sys
from PySide import QtGui, QtCore

class Example(QtGui.QWidget):
    
    def __init__(self):
        super(Example, self).__init__()
        
        self.initUI()
        
    def initUI(self):      

        self.pbar = QtGui.QProgressBar(self)
        self.pbar.setGeometry(30, 40, 200, 25)

        self.btn = QtGui.QPushButton('Start', self)
        self.btn.move(40, 80)
        self.btn.clicked.connect(self.doAction)

        self.timer = QtCore.QBasicTimer()
        self.step = 0
        
        self.setGeometry(300, 300, 280, 170)
        self.setWindowTitle('QtGui.QProgressBar')
        self.show()
        
    def timerEvent(self, e):
      
        if self.step >= 100:
            self.timer.stop()
            self.btn.setText('Finished')
            return
        self.step = self.step + 1
        self.pbar.setValue(self.step)

    def doAction(self):
      
        if self.timer.isActive():
            self.timer.stop()
            self.btn.setText('Start')
        else:
            self.timer.start(100, self)
            self.btn.setText('Stop')
        
def main():
    
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

</pre>

<p>
In our example we have a horizontal progress bar and a push button. 
The push button starts and stops the progress bar.
</p>

<pre class="explanation">
self.pbar = QtGui.QProgressBar(self)
</pre>

<p>
This is a <code>QtGui.QProgressBar</code> constructor.
</p>

<pre class="explanation">
self.timer = QtCore.QBasicTimer()
</pre>

<p>
To activate the progress bar, we use the timer object.
</p>

<pre class="explanation">
self.timer.start(100, self)
</pre>

<p>
To launch the timer events, we call the <code>start()</code> method. 
This method has two parameters. The timeout and the object, 
which will receive the events.
</p>

<pre class="explanation">
def timerEvent(self, e):
  
    if self.step >= 100:
        self.timer.stop()
        self.btn.setText('Finished')
        return
    self.step = self.step + 1
    self.pbar.setValue(self.step)
</pre>

<p>
Each <code>QtCore.QObject</code> and its descendants have a <code>timerEvent()</code>
event handler. In order to react to timer events, we reimplement the event handler.
We update the self.step variable and set a new value for the progress bar widget. 
</p>

<pre class="explanation">
def doAction(self):
  
    if self.timer.isActive():
        self.timer.stop()
        self.btn.setText('Start')
    else:
        self.timer.start(100, self)
        self.btn.setText('Stop')
</pre>

<p>
Inside the doAction() method, we start and stop the timer. 
</p>


<img src="/img/gui/pyside/progressbar.png" alt="QtGui.QProgressBar">
<div class="figure">Figure: QtGui.QProgressBar</div>


<h2>QtGui.QCalendarWidget</h2>


<p>
The <code>QtGui.QCalendarWidget</code> provides a monthly based calendar widget.
It allows a user to select a date in a simple and intuitive way.
</p>


<pre class="code">
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode PySide tutorial 

This example shows a QtGui.QCalendarWidget widget.

author: Jan Bodnar
website: zetcode.com 
last edited: August 2011
"""

import sys
from PySide import QtGui, QtCore

class Example(QtGui.QWidget):
    
    def __init__(self):
        super(Example, self).__init__()
        
        self.initUI()
        
    def initUI(self):      

        cal = QtGui.QCalendarWidget(self)
        cal.setGridVisible(True)
        cal.move(20, 20)
        cal.clicked[QtCore.QDate].connect(self.showDate)
        
        self.lbl = QtGui.QLabel(self)
        date = cal.selectedDate()
        self.lbl.setText(date.toString())
        self.lbl.move(130, 260)
        
        self.setGeometry(300, 300, 350, 300)
        self.setWindowTitle('Calendar')
        self.show()
        
    def showDate(self, date):     
        self.lbl.setText(date.toString())
        
def main():
    
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
</pre>

<p>
The example has a calendar widget and a label widget. 
The currently selected date is displayed in the label widget.
</p>

<pre class="explanation">
self.cal = QtGui.QCalendarWidget(self)
</pre>

<p>
We construct a calendar widget.
</p>


<pre class="explanation">
cal.clicked[QtCore.QDate].connect(self.showDate)
</pre>

<p>
If we select a date from the widget, a <code>clicked[QtCore.QDate]</code> 
signal is emitted. We connect this signal to the user defined 
<code>showDate()</code> method.
</p>

<pre class="explanation">
def showDate(self, date):     
    self.lbl.setText(date.toString())
</pre>

<p>
We retrieve the selected date calling the <code>selectedDate()</code> method. 
Then we transform the date object into string and set it to the label widget.
</p>

<img src="/img/gui/pyside/calendar.png" alt="QtGui.QCalendarWidget widget">
<div class="figure">Figure: QtGui.QCalendarWidget widget</div>


<p>
In this part of the PySide tutorial, we covered several widgets. 
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 
<br> 


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>

<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified August 28, 2011  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

